package org.geektimes.configuration.microprofile.config;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * @author :   chuan
 * @date :   2021/03/17
 */
public class DefaultClassTypeConverter {

    private static final Map<Class<?>, IConverter> commonTypesCache = new HashMap<>(32);

    static {
        loadInitializingConverter();
    }

    private DefaultClassTypeConverter() {
    }

    private static void loadInitializingConverter(){
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();

        ServiceLoader<IConverter> serviceLoader = ServiceLoader.load(IConverter.class, classLoader);
        Iterator<IConverter> iterator = serviceLoader.iterator();

        while (iterator.hasNext()) {
            IConverter converter = iterator.next();
            commonTypesCache.put(converter.getClassType(), converter);
        }
    }

    public static <T> IConverter<T> getClassTypeConverter(Class<T> c){
        return commonTypesCache.get(c);
    }
}
